#include "basestationmodel.h"
#include <QRandomGenerator>

BaseStationModel::BaseStationModel(QObject *parent)
    : QAbstractListModel(parent)
    , m_updateTimer(new QTimer(this))
{
    initializeStations();
    
    connect(m_updateTimer, &QTimer::timeout, this, &BaseStationModel::updateStations);
    m_updateTimer->start(3000); // 每3秒更新
}

void BaseStationModel::initializeStations()
{
    // 模拟某地区范围：北纬39.90-40.00，东经116.30-116.50（北京地区）
    QStringList areas = {"朝阳", "海淀", "东城", "西城", "丰台"};
    
    for (int i = 0; i < 50; ++i) {
        BaseStation station;
        station.id = QString("BS%1").arg(i + 1, 3, 10, QChar('0'));
        station.name = QString("%1区基站-%2").arg(areas[i % areas.size()]).arg(i + 1);
        station.latitude = 39.90 + QRandomGenerator::global()->bounded(100) / 1000.0; // 0.000 到 0.100
        station.longitude = 116.30 + QRandomGenerator::global()->bounded(200) / 1000.0; // 0.000 到 0.200
        station.status = "normal";
        station.signalStrength = 80.0 + QRandomGenerator::global()->bounded(20);
        station.connectedUsers = 10 + QRandomGenerator::global()->bounded(50);
        
        m_stations.append(station);
    }
}

void BaseStationModel::updateStations()
{
    // 随机更新部分基站状态
    for (int i = 0; i < m_stations.size(); ++i) {
        auto &station = m_stations[i];
        QString oldStatus = station.status;
        
        // 信号强度波动（减小变化幅度以降低状态变化频率）
        double change = (QRandomGenerator::global()->bounded(100) - 50) / 25.0; // -2.0 到 2.0
        station.signalStrength = qMax(30.0, qMin(100.0, station.signalStrength + change));
        
        // 用户数波动
        int userChange = QRandomGenerator::global()->bounded(11) - 5; // -5 到 5
        station.connectedUsers = qMax(0, qMin(100, station.connectedUsers + userChange));
        
        // 根据信号强度更新状态
        if (station.signalStrength >= 80) {
            station.status = "normal";
        } else if (station.signalStrength >= 65) {
            station.status = "warning";
        } else if (station.signalStrength >= 40) {
            station.status = "critical";
        } else {
            station.status = "offline";
        }
        
        // 0.5%概率随机离线（降低异常频率）
        if (QRandomGenerator::global()->bounded(1000) < 5) {
            station.status = "offline";
            station.signalStrength = 0;
        }
        
        // 发送状态变化信号
        if (oldStatus != station.status) {
            emit stationStatusChanged(station.id, oldStatus, station.status);
            
            // 如果从正常变为异常，立即触发告警（与地图显示同步）
            if (oldStatus == "normal" && station.status != "normal") {
                QString message;
                QString severity;
                
                if (station.status == "warning") {
                    message = QString("基站 %1 信号质量下降").arg(station.id);
                    severity = "warning";
                } else if (station.status == "critical") {
                    message = QString("基站 %1 信号严重不足").arg(station.id);
                    severity = "critical";
                } else if (station.status == "offline") {
                    message = QString("基站 %1 离线").arg(station.id);
                    severity = "critical";
                }
                
                emit stationAlarm(station.id, message, severity);
            }
        }
        
        QModelIndex idx = index(i);
        emit dataChanged(idx, idx);
    }
    
    // 发送统计更新信号
    emit statisticsChanged(getAbnormalCount(), getAvgSignalQuality());
}

int BaseStationModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_stations.count();
}

QVariant BaseStationModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_stations.count())
        return QVariant();

    const BaseStation &station = m_stations[index.row()];

    switch (role) {
    case IdRole:
        return station.id;
    case NameRole:
        return station.name;
    case LatitudeRole:
        return station.latitude;
    case LongitudeRole:
        return station.longitude;
    case StatusRole:
        return station.status;
    case SignalStrengthRole:
        return station.signalStrength;
    case ConnectedUsersRole:
        return station.connectedUsers;
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> BaseStationModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[IdRole] = "stationId";
    roles[NameRole] = "stationName";
    roles[LatitudeRole] = "latitude";
    roles[LongitudeRole] = "longitude";
    roles[StatusRole] = "status";
    roles[SignalStrengthRole] = "signalStrength";
    roles[ConnectedUsersRole] = "connectedUsers";
    return roles;
}

QVariantMap BaseStationModel::getStationInfo(int index) const
{
    QVariantMap info;
    if (index < 0 || index >= m_stations.count())
        return info;

    const BaseStation &station = m_stations[index];
    info.insert("stationId", station.id);  // 使用 stationId 而不是 id
    info.insert("stationName", station.name);  // 使用 stationName 而不是 name
    info.insert("latitude", station.latitude);
    info.insert("longitude", station.longitude);
    info.insert("status", station.status);
    info.insert("signalStrength", station.signalStrength);
    info.insert("connectedUsers", station.connectedUsers);
    
    return info;
}

int BaseStationModel::getAbnormalCount() const
{
    int count = 0;
    for (const auto &station : m_stations) {
        if (station.status != "normal") {
            count++;
        }
    }
    return count;
}

double BaseStationModel::getAvgSignalQuality() const
{
    double total = 0;
    int count = 0;
    for (const auto &station : m_stations) {
        if (station.status != "offline") {
            total += station.signalStrength;
            count++;
        }
    }
    return count > 0 ? total / count : 0;
}

